/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Semaforos;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author 21322325
 */
public class Hilo extends Thread {

    /**
     * @param args the command line arguments
     */
    public String id;
    public Semaphore semaforo;
    Random rand = new Random();
    
    //Constructor
    public Hilo(String i, Semaphore semaforo){
        this.id = i;
        this.semaforo = semaforo;
    }
    
    private void ocupado(){
        try {
            Thread.sleep(2000);
            System.out.println("Soy el " + this.id + " y estoy ocupado. No me molestes!!");
        } catch (InterruptedException ex) {
            Logger.getLogger(Hilo.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void run () {
        System.out.println("No crítica en " + id);
        this.ocupado();
        //Sección crítica
        try{
            semaforo.acquire();
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Entrando SECCION CRITICA : " + this.id);
        this.ocupado();
        System.out.println("Salgo de la SECCION CRITICA : " +this.id);
        semaforo.release();
    }   
}
